<template>
    <div>
        <el-row>
            <el-col :span="24">
                <p class="title" style="font-size:30px;">电子档提交</p>
                <p>您选择文学主题为：<span style="color:#409EFF;font-size:20px;font-weight:700;font-family:PingFang SC; ">{{prjClass}}</span></p>
                <p class="status">当前状态：
                    <span style="color: #409EFF;font-size:20px;font-weight:700;font-family:PingFang SC;">“{{statusMsg}}”</span>
                    ，允许提交时间段：{{startUploadTime}} ~ {{endUploadTime}}</p>
            </el-col>
        </el-row>
        <el-row>
            提示：投稿作品必须采用WORD或PDF或文本（txt）格式，请直接上传只带有作品题目的作品，系统会自动命名,多次提交会覆盖历史版本
        </el-row>
        <p></p>
        <el-row style="color:#f6503a;font-size:20px;font-weight:700;font-family:PingFang SC; ">
            注意：上传云端后，请确认
        </el-row>
        <p></p>
        <el-upload ref="fileUploadForm" action="" :multiple="false" :auto-upload="false" :show-file-list="false"
             
            :http-request="handleFileUploadSubmit" 
            :on-change="handleFileChanged" 
            accept=".txt,.pdf,.doc,.docx"
            :on-success="handleSuccess">
            <el-row>
                <el-col style="display: flex; text-align: center; width: 400px">
                    <el-input :value="currentFileName" placeholder="请选择文件" readonly />
                    <el-button type="primary" :disabled="uploadValid"  style="margin-left: 20px" >选择文件</el-button>
                </el-col>
            </el-row>
        </el-upload>
        
        <el-row style="margin-top: 30px; margin-bottom: 30px">
            <el-col style="text-align: center">
                <el-button  @click="clearFile">清空</el-button>
                <el-button type="success"  style="margin-left: 20px" @click="uploadPrj">上传云端</el-button>
                <el-button type="success" style="margin-left: 20px" @click="submitFile">确认</el-button>
            </el-col>
        </el-row>
        <el-row>
            <el-button type="primary" icon="el-icon-download" v-if="this.havesubmitPrj.prjUrl!=null" :style="{fontSize: '16px', fontWeight: 'bold'}" @click="downloadFile">
                {{havesubmitPrj.prjRealname}}下载文件
            </el-button>
        </el-row>
        <!-- Undo：预览文件 (未实现)；https://blog.csdn.net/qq_25519615/article/details/133024088  txt
        https://www.cnblogs.com/lynna/p/17295419.html  docx pdf
        -->

    </div>
</template>

<script lang="js">
    import apiService from 'axios'

    export default {
        name: 'UploadDemo',
        data() {
            return {
                
                startUploadTime:"2024-4-25 09:30:00",
                endUploadTime: "2024-5-30 23:55:00",
                statusMsg:null,
                uploadValid:false,
                // 当前已选择的文件的文件名
                currentFileName: '',
                // 待上传的文件列表
                file: null,
                prjClass:null,
                classes:[],
                havesubmitPrj:{
                    prjIndex: null,
                    prjConid: null,
                    prjRealname: null,
                    prjVirtname: null,
                    prjUrl: null,
                    prjCreatetime: null,
                    prjUpdatetime: null,
                    prjPublicfirstgrad:null,
                    prjFinalscore:null,
                    prjPublicfinalgrad:null,
                    prjScore: null,
                    prjStatus: null
                },
                postprojectData:{
                    prjIndex:null,
                    prjConid:null,
                    prjRealname:null,
                    prjVirtname:null,
                    prjUrl:null,
                    prjCreatetime:null,
                    prjUpdatetime:null,
                    prjPublicfirstgrad: null,
                    prjFinalscore: null,
                    prjPublicfinalgrad: null,
                    prjScore:null,
                    prjStatus:null
                }
            };
        },
        methods: {
             getTime() {
                var nowTime = Date.parse(new Date());
                return nowTime;
            },
            ValidDateStage(){
                var newDate = this.getTime();

                var startTime = Date.parse(new Date(this.startUploadTime));
                var endTime = Date.parse(new Date(this.endUploadTime));
                if (newDate > startTime && newDate < endTime) {
                    this.uploadValid =false;
                }else{
                    this.uploadValid =true ;
                }
            },
            downloadFile() {
                // 创建隐藏的可下载链接
                const link = document.createElement('a');
                link.style.display = 'none';
                link.href = this.havesubmitPrj.prjUrl|| this.postprojectData.prjUrl;
                link.download = this.havesubmitPrj.prjRealname|| this.postprojectData.prjRealname;

                // 触发下载
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            },
            /**
             * 文件状态改变时的操作
             * @param {Object} selectedFile 选择的文件对象
             * */
            handleFileChanged(selectedFile) {
                
                // 文件列表修改为选择的文件
                this.file = selectedFile;
                console.log(this.file);
                console.log(selectedFile);
                // 提示框展示为选择的文件的文件名
                var filename = selectedFile.name;
                var fileName = filename.split('.').slice(0, -1).join('.');
                var PatternFileName = "文学奖大赛-"+ this.$store.state.userdata.userName+"-"+ fileName + "-"+this.$store.state.userdata.userClass
                this.currentFileName = PatternFileName;
                this.postprojectData.prjRealname = this.currentFileName;
                
                
            },

            /**
             * 清空待上传的文件列表
             * */
            clearFile() {
                // 待上传的文件列表清空
                this.file = null;
                // 提示框展示的文件名清空
                this.currentFileName = '';
                this.postprojectData.prjRealname=null;
                this.postprojectData.prjVirtname= null;
                this.postprojectData.prjUrl = null;
            },
            
            /**
             * 点击【上传】按钮时要进行的操作
             * */
            uploadPrj() {
                var newDate = this.getTime();
                
                var startTime = Date.parse(new Date(this.startUploadTime));
                var endTime = Date.parse(new Date(this.endUploadTime));
                if(newDate>startTime && newDate<endTime){
                    const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain'];
                    console.log(this.file);
                    // TODO 还可以进行文件校验等操作
                    if (this.file == null) {
                        this.$alert('请选择文件后再上传！', '提示', {
                            type: 'warning'
                        });
                        return;
                    }
                    const fileMimeType = this.file.raw.type;
                    if (!allowedTypes.includes(fileMimeType)) {
                        alert('只能上传PDF、Word或文本文件!');
                        // 清除已选中的非法文件
                        this.clearFile();
                        return;
                    }
                    // 校验无误将要上传，这里会调用 http-request 所绑定的方法
                    this.$refs.fileUploadForm.submit();
                }else{
                    this.$message.error("不在提交事件段内不允许上传");
                }
                
            },
            async fetchData(){
                this.$axios({
                    method: 'get',
                    url: 'http://localhost:8080/project/find',
                    params:{
                        ConId:this.$store.state.userdata.userId
                    },

                }).then(res => {
                    if (res.data.code == 1) {
                        this.havesubmitPrj=res.data.data;
                        this.statusMsg="已提交，可更新"
                    }else{
                        this.statusMsg = "待提交"
                    }

                })
               this.$axios({
                    method: 'get',
                    url: 'http://localhost:8080/class',
                }).then(res => {
                    if (res.data.code == 1) {
                        this.classes = res.data.data;
                        this.prjClass = res.data.data[this.$store.state.userdata.userClass - 1].className;
                        console.log("classes",this.prjClass);
                    }
                })
                
            },
             async handleSuccess(response, file) {
                // 假设后端返回的是上传到OSS后的图片URL
                const fileName =this.file.name;
                var fileName1 = fileName.split('.').slice(0, -1).join('.');
                this.postprojectData.prjRealname = "文学奖大赛-" + this.$store.state.userdata.userName + "-" + fileName1 + "-" + this.$store.state.userdata.userClass;
                this.postprojectData.prjUrl = response.data.data;
                // 创建一个新的URL对象
                const parsedUrl = new URL(response.data.data);
                 // 获取路径的最后一部分作为文件名.slice(0, VirtfileName.lastIndexOf('.'))
                const VirtfileName = parsedUrl.pathname.split('/').pop();
                console.log("VirtfileName",VirtfileName);
                this.postprojectData.prjVirtname = VirtfileName;
                
            },
            /**
             * 发送文件上传的网络请求
             * */
            handleFileUploadSubmit({ file }) {
                 var newDate = this.getTime();

                var startTime = Date.parse(new Date(this.startUploadTime));
                var endTime = Date.parse(new Date(this.endUploadTime));
                if (newDate > startTime && newDate < endTime) {
                    // 创建一个表单，用于存放请求数据(主要是文件)
                    const fileFormData = new FormData();
                    // 在表单中添加要发送给接口的数据
                    
                    fileFormData.append('file', file);
                    // 使用 axios 发送文件上传请求，并监听文件上传进度
                    try {
                        this.$axios({
                            method: 'post',
                            url: 'http://localhost:8080/image/upload',
                            data: fileFormData,

                        }).then(res => {
                            if (res.data.code == 1) {
                                this.handleSuccess(res);
                                this.postprojectData.prjConid = this.$store.state.userdata.userId;
                                this.$message.success('上传文件成功！');
                            }

                        })

                    } catch (error) {
                        console.error('上传失败:', error);
                        this.$message.error('上传图片到OSS失败!');
                    }
                }else{
                    this.$message.error("不在允许时间段内！")
                }
                
                
            },
            submitFile(){
                var newDate = this.getTime();

                var startTime = Date.parse(new Date(this.startUploadTime));
                var endTime = Date.parse(new Date(this.endUploadTime));
                if (newDate > startTime && newDate < endTime) {
                    this.$confirm('提交后作品会被记录, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        this.$axios({
                            method: 'post',
                            url: "http://localhost:8080/project/submit",
                            data: JSON.stringify(this.postprojectData),
                            headers: { 'Content-Type': 'application/json' },
                        }).then(res => {
                            if (res.data.code == 1) {
                                this.$message({
                                    type: 'success',
                                    message: '提交成功!'
                                });
                                this.fetchData();
                            } else {
                                this.$message({
                                    type: 'error',
                                    message: '提交失败，请联系管理员!'
                                });
                            }
                        })

                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消提交'
                        });
                    });
                }else{
                    this.$message.error("不在提交事件段内不允许上传");
                }
                
            }
        },
        mounted() {
    
            this.fetchData();    
            this.ValidDateStage();
        },
    }
</script>
<style scoped>
    .title {
        font-size: 24px;
        color: #409EFF;
        margin-bottom: 10px;
    }

    .status {
        font-size: 16px;
        color: #666;
    }
</style>